from django.contrib.auth.backends import ModelBackend
import re
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from .contants import EMAIL_VERIFY_TOKEN_EXPIRE
from itsdangerous import BadData
from django.db.models import ObjectDoesNotExist


from users.models import User


def check_email_verify_url(token):
    s = Serializer(settings.SECRET_KEY, EMAIL_VERIFY_TOKEN_EXPIRE)
    try:
        mail_user = s.loads(token)
    except BadData:
        return None
    else:
        user_id = mail_user.get('user_id')
        user_email = mail_user.get('email')


    try:
        user = User.objects.get(id=user_id, email=user_email)
    except ObjectDoesNotExist:
        return None
    else:
        return user


def generate_email_verify_url(user):
    base_mail_url = settings.EMAIL_VERIFY_URL
    s = Serializer(settings.SECRET_KEY, EMAIL_VERIFY_TOKEN_EXPIRE)
    data = {'user_id': user.id, 'email': user.email}
    mail_token = s.dumps(data)
    return base_mail_url + '?token=' + mail_token.decode()


def getUserByAccount(account):
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if request is None:
            try:
                user = User.objects.get(username=username, is_superuser=True)
            except:
                user = None

            if user and user.check_password(password):
                return user

            return None

        if username is None or password is None:
            return None

        user = getUserByAccount(username)
        if user and user.check_password(password):
            return user

        return None

